package com.ysstech.reportworld.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ysstech.common.entity.PageBean;
import com.ysstech.common.exception.BusinessException;
import com.ysstech.common.service.DicvalueService;
import com.ysstech.reportworld.entity.*;
import com.ysstech.reportworld.enums.ReportWorldEnum;
import com.ysstech.reportworld.enums.ReportWorldStatusEnum;
import com.ysstech.reportworld.mapper.TableDetailStandardCheckMapper;
import com.ysstech.reportworld.service.TableDetailStandardCheckService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 报表世界字段校验规则 服务实现类
 * </p>
 *
 * @author lishuangliang
 * @since 2023-01-11
 */
@Service
@Slf4j
public class TableDetailStandardCheckServiceImpl extends ServiceImpl<TableDetailStandardCheckMapper, TableDetailStandardCheck> implements TableDetailStandardCheckService {

    @Autowired
    private DicvalueService dicvalueService;


    /**
     * 获取字段校验规则信息
     *
     * @param tableDetailStandardCheck
     * @param pageBean
     * @return
     * @throws Exception
     */
    public PageBean<TableDetailStandardCheck> queryAllTableDetailStandardCheck(TableDetailStandardCheck tableDetailStandardCheck, PageBean pageBean) throws Exception {
        QueryWrapper<TableDetailStandardCheck> wrapper = getQueryWrapper(tableDetailStandardCheck);
        IPage pageScheduleLog = this.page(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()), wrapper);
        this.switchedListTableDetailStandardCheck(pageScheduleLog.getRecords());
        return new PageBean<>(pageScheduleLog);
    }

    /**
     * 处理查询条件信息
     *
     * @param tableDetailStandardCheck
     * @return
     */
    private QueryWrapper<TableDetailStandardCheck> getQueryWrapper(TableDetailStandardCheck tableDetailStandardCheck) {
        if (null == tableDetailStandardCheck) {
            return null;
        }
        QueryWrapper<TableDetailStandardCheck> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(tableDetailStandardCheck.getColumnName())) {
            wrapper.eq("COLUMN_NAME", tableDetailStandardCheck.getColumnName());
        }
        if (StringUtils.isNotBlank(tableDetailStandardCheck.getColumnChineseName())) {
            wrapper.like("COLUMN_CHINESE_NAME", tableDetailStandardCheck.getColumnChineseName());
        }
        if (null != tableDetailStandardCheck.getColumnType()) {
            wrapper.like("COLUMN_TYPE", tableDetailStandardCheck.getColumnType());
        }
        if (null != tableDetailStandardCheck.getStatus()) {
            wrapper.eq("STATUS", tableDetailStandardCheck.getStatus());
        }
        return wrapper;
    }

    /**
     * 类型，机构等中文的转换
     *
     * @param list
     * @return
     * @throws Exception
     */
    private List<TableDetailStandardCheck> switchedListTableDetailStandardCheck(List<TableDetailStandardCheck> list) throws Exception {
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }
        //字段类型
        Map<String, String> mapColumnType = dicvalueService.getCacheDicValueMap(ReportWorldEnum.COLUMN_TYPE.getCode());
        //状态
        Map<String, String> mapStatus = dicvalueService.getCacheDicValueMap(ReportWorldEnum.REPORT_STATUS.getCode());
        for (TableDetailStandardCheck tableDetailStandardCheck : list) {
            if (null == tableDetailStandardCheck) {
                continue;
            }
            // 字段类型
            if (null != mapColumnType && mapColumnType.containsKey(String.valueOf(tableDetailStandardCheck.getColumnType()))) {
                tableDetailStandardCheck.setStrColumnType(mapColumnType.get(String.valueOf(tableDetailStandardCheck.getColumnType())));
            }
            //状态
            if (null != mapStatus && mapStatus.containsKey(String.valueOf(tableDetailStandardCheck.getStatus()))) {
                tableDetailStandardCheck.setStrStatus(mapStatus.get(String.valueOf(tableDetailStandardCheck.getStatus())));
            }
        }
        return list;
    }


    /**
     * 表字段的时候检验字段规范
     *
     * @return
     * @throws Exception
     */
    public void tableDetailStandardCheckInfo(TableDetail tableDetail) throws Exception {
        if (null == tableDetail || StringUtils.isBlank(tableDetail.getColumnName())) {
            log.error("没有获取到要检查的表字段信息！");
            return;
        }
        QueryWrapper<TableDetailStandardCheck> wrapper = new QueryWrapper<>();
        wrapper.eq("STATUS", ReportWorldStatusEnum.REPORT_NORMAL.getCode());
        List<TableDetailStandardCheck> list = this.list(wrapper);
        if (CollectionUtils.isEmpty(list)) {
            log.info("没有获取到字段的检验规则信息！");
            return;
        }
        if (StringUtils.isBlank(tableDetail.getColumnChineseName())) {
            throw new BusinessException(tableDetail.getColumnName() + "字段没有中文注释");
        }
        //字段类型
        Map<String, String> mapColumnType = dicvalueService.getCacheDicValueMap(ReportWorldEnum.COLUMN_TYPE.getCode());
        for (TableDetailStandardCheck check : list) {
            if (null == check || StringUtils.isBlank(check.getColumnName())) {
                continue;
            }
            // 中文名称相同的字段名称比较
            if (StringUtils.isNotBlank(check.getColumnChineseName()) && StringUtils.isNotBlank(tableDetail.getColumnChineseName())
                    && tableDetail.getColumnChineseName().equals(check.getColumnChineseName())
                    && !tableDetail.getColumnName().equals(check.getColumnName())) {
                throw new BusinessException("中文注释为【" + check.getColumnChineseName() + "】按照规范字段名称应该是【" + check.getColumnName() + "】");
            }
            if (!tableDetail.getColumnName().equals(check.getColumnName())) {
                continue;
            }
            // 中文名称
            if ((StringUtils.isNotBlank(check.getColumnChineseName()) && StringUtils.isBlank(tableDetail.getColumnChineseName())) ||
                    (StringUtils.isNotBlank(check.getColumnChineseName()) && StringUtils.isNotBlank(tableDetail.getColumnChineseName())
                            && !tableDetail.getColumnChineseName().equals(check.getColumnChineseName()))) {
                throw new BusinessException(tableDetail.getColumnName() + "字段的中文注释按照规范应该为【" + check.getColumnChineseName() + "】");
            }
            // 字段类型
            if ((null != check.getColumnType() && null == tableDetail.getColumnType()) ||
                    (null != check.getColumnType() && null != tableDetail.getColumnType()
                            && tableDetail.getColumnType().intValue() != check.getColumnType().intValue())) {
                throw new BusinessException(tableDetail.getColumnName() + "字段类型应该为【" + mapColumnType.get(String.valueOf(check.getColumnType())) + "】");
            }
            // 字段长度
            if ((null != check.getColumnLength() && null == tableDetail.getColumnLength()) ||
                    (null != check.getColumnLength() && null != tableDetail.getColumnLength()
                            && tableDetail.getColumnLength().intValue() != check.getColumnLength().intValue())) {
                throw new BusinessException(tableDetail.getColumnName() + "字段长度应该为【" + check.getColumnLength() + "】");
            }
            // 小数位数
            if ((null != check.getColumnDecimal() && null == tableDetail.getColumnDecimal()) ||
                    (null != check.getColumnDecimal() && null != tableDetail.getColumnDecimal()
                            && tableDetail.getColumnDecimal().intValue() != check.getColumnDecimal().intValue())) {
                throw new BusinessException(tableDetail.getColumnName() + "字段小数应该为【" + check.getColumnDecimal() + "】");
            }
            // 是否主键
            if ((null != check.getPrimaryKey() && null == tableDetail.getPrimaryKey()) ||
                    (null != check.getPrimaryKey() && null != tableDetail.getPrimaryKey()
                            && tableDetail.getPrimaryKey().intValue() != check.getPrimaryKey().intValue())) {
                throw new BusinessException(tableDetail.getColumnName() + (1 == check.getPrimaryKey() ? "应该是主键" : "不能为主键"));
            }
            // 是否为空
            if ((null != check.getColumnNull() && null == tableDetail.getColumnNull()) ||
                    (null != check.getColumnNull() && null != tableDetail.getColumnNull()
                            && tableDetail.getColumnNull().intValue() != check.getColumnNull().intValue())) {
                throw new BusinessException(tableDetail.getColumnName() + (1 == check.getColumnNull() ? "应该为空" : "不能为空"));
            }
            // 默认值
            if ((StringUtils.isNotBlank(check.getColumnDefault()) && StringUtils.isBlank(tableDetail.getColumnDefault())) ||
                    StringUtils.isNotBlank(check.getColumnDefault()) && StringUtils.isNotBlank(tableDetail.getColumnDefault())
                            && !tableDetail.getColumnDefault().toUpperCase().equals(check.getColumnDefault().toUpperCase())) {
                boolean falg = false;
                if (StringUtils.isNotBlank(tableDetail.getColumnDefault())) {
                    List<TableColumnDefaultVO> defaultVOS = JSON.parseArray(tableDetail.getColumnDefault(), TableColumnDefaultVO.class);
                    if (!CollectionUtils.isEmpty(defaultVOS)) {
                        for (TableColumnDefaultVO vo : defaultVOS) {
                            if (null == vo || StringUtils.isBlank(vo.getFvalue())) {
                                continue;
                            }
                            if (vo.getFvalue().equals(check.getColumnDefault())) {
                                falg = true;
                                break;
                            }
                        }
                    }
                }
                if (!falg) {
                    throw new BusinessException(check.getColumnName() + "默认值应该为：" + check.getColumnDefault());
                }
            }
        }

    }
}
